/**
 * 
 */
package poc.android.command;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import poc.android.weather.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
 * @author Jason
 *
 */
public class LinuxCommandActivity extends Activity {

	Button btnRunCommand;
	EditText txtCommand;
	EditText txtResult;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.linux_command_main_activity);
		
		this.setupWidgets(savedInstanceState);
	}

	/**
	 * 
	 * @param pBundle
	 */
	private void setupWidgets(Bundle pBundle) {
		this.btnRunCommand=(Button) this.findViewById(R.id.btnLinuxRunCommand);
		this.btnRunCommand.setOnClickListener(new Button.OnClickListener() {
			//@Override
			public void onClick(View v) {
				String aResult=null;
				
				aResult=onRunClick();
				txtResult.setText(aResult);
			}
		});
		this.txtCommand=(EditText) this.findViewById(R.id.txtLinuxCommand);
		this.txtResult=(EditText) this.findViewById(R.id.txtLinuxResult);
	}
	
	/**
	 * PS. a demo on how to run a linux command... might have buffer overflow 
	 * cases... Commands tested:
	 * <ul>
	 * 	<li>ls / ls -l / ls dev</li>
	 * </ul>
	 * @return
	 */
	private String onRunClick() {
		StringBuilder aSB=new StringBuilder(500);		
		String aCmd=this.txtCommand.getText().toString();
		
		if (aCmd!=null && aCmd.trim().length()>0) {
			Process aProc=null;
			BufferedReader aReader=null;
			
			try {
				String aLine=null;
				
				aProc=Runtime.getRuntime().exec(aCmd, null, new File("/"));
				aReader=new BufferedReader(new InputStreamReader(aProc.getInputStream()));
				
				while ((aLine=aReader.readLine())!=null) {
					// TODO move this line.separator to Application level etc
					if (aSB.length()>0) aSB.append(System.getProperty("line.separator"));
					aSB.append(aLine);
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("[LinuxCommandActivity][onRunClick] failed to process command~", e);
				
			} finally {
				if (aReader!=null) try { aReader.close(); } catch (Exception e) {}
				if (aProc!=null) try { aProc.destroy(); } catch (Exception e) {}
			}
		}
		return aSB.toString();
	}
	
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

}
